package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;

import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.GetRedLvAdapter;
import com.ycsj.goldmedalnewconcept.bean.GetRedInfo;
import com.ycsj.goldmedalnewconcept.bean.GetRedInfo.RedPacketsBean.PersonsBean;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;

/**
 * 创建日期：2017/11/7  14:17
 * 描述:红包记录
 * 作者:张伟
 */

@SuppressLint("NewApi")
public class RedPackageGetRecordActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    //正常请求
    public static final int NORMAL = 0X110;

    //下拉刷新
    public static final int PULLTOREFRESH = 0X120;


    //返回
    private LinearLayout llBack;

    //加载视图
    private LinearLayout llLoading;

    //空数据
    private LinearLayout llEmpty;

    //下拉刷新控件
    private PullToRefreshLayout ptrl;

    //列表控件
    private ListView lv;

    //头布局
    private View headView;
    //头布局的布局控件
    private TextView tvSend;//总发出
    private TextView tvNum;//总领取人数
    private TextView tvUse;//总使用
    private ImageView iv_share;//分享
    

    //列表控件的数据集合
    private List<GetRedInfo.RedPacketsBean.PersonsBean> oldDatas;
    private String redid;
    private GetRedLvAdapter adapter;

	private String title;

	private String Money;

    
    

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_red_package_get_record);

        //设置状态栏颜色
        setBar();

        //获取红包ID
        getRedId();

        //初始化View的方法
        initViews();

        //初始化列表
        initLv();

        //设置监听
        initListener();

        //网络请求数据
        http(NORMAL);
    }


    /**
     * 网络请求的方法
     *
     * @param method
     */
    private void http(final int method) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "7");
        builder.add("redId", redid);
        builder.add("role", "3");
        Request request = new Request.Builder()
                .url(Constant.SERVER_URL+"RedPacketMsg").post(builder.build())
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //请求失败,主线程更新UI操作
                        if (llLoading != null) {
                            llLoading.setVisibility(View.GONE);
                        }
                        Toast.makeText(RedPackageGetRecordActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Response arg0) throws IOException {
                try {
                    //请求成功
                    //获取服务器返回的json数据
                    String json = arg0.body().string();
                    Log.e("test", json);
                    if (!TextUtils.isEmpty(json)) {
                        final GetRedInfo redInfo = GsonUtil.jsonToBean(json, GetRedInfo.class);
                        final GetRedInfo.RedPacketsBean redPackets = redInfo.getRedPackets();
                        //获取列表数据
                        final List<GetRedInfo.RedPacketsBean.PersonsBean> skins = redPackets.getPersons();
                        if (null != skins && skins.size() != 0) {
                        	
                        	Collections.reverse(skins);//倒序处理
                        	
                            //证明有列表数据,更新主界面
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    //设置头部数据
                                    tvSend.setText(redPackets.getMoney() + "");
                                    tvNum.setText(redPackets.getRobbedPerson() + " 人");
//                                    tvNum.setText(skins.size() + " 人");
                                    tvUse.setText(redPackets.getUsedMoney() + "");

                                    if (method == NORMAL) {
                                        //正常请求
                                        if (llLoading != null) {
                                            llLoading.setVisibility(View.GONE);
                                        }
                                        oldDatas.addAll(skins);
                                        lv.setAdapter(adapter);
                                    } else {
                                        //下拉刷新
                                        oldDatas.clear();
                                        oldDatas.addAll(skins);
                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
                                        adapter.notifyDataSetChanged();
                                        
                                    }
                                }
                            }); 
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //证明没有数据,显示空视图,隐藏加载框
                                    if (method == NORMAL) {
                                        tvSend.setText(Money+"");
                                        tvNum.setText("0 人");
                                        tvUse.setText("0");
                                        //正常加载
                                        if (llLoading != null) {
                                            llLoading.setVisibility(View.GONE);
                                        }
                                        if (llEmpty != null) {
                                            llEmpty.setVisibility(View.VISIBLE);
                                        }
                                        lv.setAdapter(adapter);
                                    } else {
                                        //下拉刷新
                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化View的方法
     */
    private void initViews() {
        llBack = (LinearLayout) findViewById(R.id.ll_back);
        llLoading = (LinearLayout) findViewById(R.id.ll_loading);
        ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_view);
        iv_share = (ImageView) findViewById(R.id.iv_share);
        
        lv = (ListView) findViewById(R.id.lv);
        llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
        headView = View.inflate(this, R.layout.lv_getred_headview, null);
        tvSend = (TextView) headView.findViewById(R.id.tv_send);
        tvNum = (TextView) headView.findViewById(R.id.tv_num);
        tvUse = (TextView) headView.findViewById(R.id.tv_use);
        
    }

    /**
     * 获取红包ID的方法
     */
    public void getRedId() {
        redid = getIntent().getStringExtra("redid");
        title = getIntent().getStringExtra("title");
        Money = getIntent().getStringExtra("Money");
        
    }

    /**
     * 初始化列表控件的方法
     */
    private void initLv() {
        oldDatas = new ArrayList<PersonsBean>();
        adapter = new GetRedLvAdapter(this, oldDatas, R.layout.item_lv_getpack);
        //给ListView添加头布局
        lv.addHeaderView(headView);
    }

    /**
     * 设置监听的方法
     */
    private void initListener() {
        llBack.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        ptrl.setOnRefreshListener(this);
    }


    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        http(PULLTOREFRESH);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                //返回
                finish();
                break;
            case R.id.iv_share:
            	//分享
            	
            	share();
            	
            	break;
        }
    }

    private void share() {
		// TODO Auto-generated method stub
    	MobSDK.init(RedPackageGetRecordActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {

				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					// http://m.moregolden.com:36356/redBag/redBag.html?rid=
					String url = Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid;
					// String url =
					// "http://139.129.213.183:36356/redBag/redBag.html?rid="+redid;
					// String url =
					// "http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid;

					String title = "来自"
							+ SPUtil.getString(RedPackageGetRecordActivity.this, "schoolName", "")
							+ "学校的红包";
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare.setTitleUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle("来自"
							+ SPUtil.getString(RedPackageGetRecordActivity.this, "schoolName", "")
							+ "学校的红包");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(title);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片

					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/redbag.png");
					// paramsToShare.setImageData(mBitmap);

					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					// paramsToShare.setSite(getString(R.string.app_name));
					paramsToShare.setSite("金牌君");
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare.setTitleUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle("来自"
							+ SPUtil.getString(RedPackageGetRecordActivity.this, "schoolName", "")
							+ "学校的红包");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(title);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("https://moregolden.com:8081/Appandroid/redbag.png");

					// paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite("金牌君");
					// paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(Constant.SERVER_tk
							+ ":36356/redBag/redBag.html?rid=" + redid);
					// paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				}
			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用

		// 启动分享GUI
		oks.show(RedPackageGetRecordActivity.this);
	}


	/**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }

}
